#!/usr/bin/perl -w
# Author: Xinwu
# Describe: 
# Completion Time: 
# Email: lexinwu@outlook.com

use strict;
use Getopt::Long;

sub USAGE {
    my $usage=<<"USAGE";
Usage: perl $0 -i <genome.gtf> -o <genome.bed> -h [help]
Options:
    -i, --infile        input genome annotation file, eg. genome.gtf
    -o, --outfile       gene position output file, eg. mouse_gene_pos.bed
    -h, --help          help messages

USAGE
        print $usage;
        exit;
}

my ($i, $o);
GetOptions(
    "h|help"        => \&USAGE, 
    "i|infile:s"    => \$i,
    "o|outfile:s"   => \$o,
) or &USAGE;
&USAGE unless ($i and $o);

open GTF, $i;
open OUT, ">$o";
print OUT "geneName\tchr\tstart\tend\n";
while(<GTF>){
    next if /^#|^$/;
    next unless (split/\t/,$_)[2] eq "gene";
    chomp;
    my($chr, $start, $end) = (split/\t/,$_)[0,3,4];
    my($gene_id, $gene_name) = $_ =~ /gene_id "(\S+)";.*gene_name "(\S+)";/;
    print OUT "$gene_name\t$chr\t$start\t$end\n";
}
close GTF;
close OUT;